function loadWorkers() {
    fetch("/api/workers")
        .then(response => response.json())
        .then(workers => {
            // 更新统计数据
            updateWorkerStats(workers);
            
            const tbody = document.querySelector("#workersTable tbody");
            if (!tbody) {
                console.error("Could not find workers table body");
                return;
            }
            // 清除现有内容
            tbody.innerHTML = "";
            
            if (!workers || workers.length === 0) {
                const noDataRow = document.createElement("tr");
                noDataRow.innerHTML = `<td colspan="8" class="text-center">暂无Worker数据</td>`;
                tbody.appendChild(noDataRow);
                return;
            }
            
            // 渲染worker数据
            workers.forEach(worker => {
                const row = document.createElement("tr");
                
                // 格式化时间
                const createdAt = new Date(worker.created_at).toLocaleString();
                const lastHeartbeat = new Date(worker.last_heartbeat).toLocaleString();
                
                // 创建复选框
                const checkboxCell = document.createElement("td");
                checkboxCell.innerHTML = `<input type="checkbox" class="worker-select" data-id="${worker.id}">`;
                
                // 创建其他单元格
                const nameCell = document.createElement("td");
                nameCell.textContent = worker.name;
                
                const idCell = document.createElement("td");
                idCell.innerHTML = `<span class="badge bg-light text-dark" style="font-size: 0.8em;">${worker.id}</span>`;
                
                const ipCell = document.createElement("td");
                ipCell.textContent = worker.ip_address;
                
                const statusCell = document.createElement("td");
                const statusClass = worker.status === "online" ? "success" : "danger";
                const heartbeatClass = worker.heartbeat_status === "healthy" ? "success" : worker.heartbeat_status === "warning" ? "warning" : "danger";
                statusCell.innerHTML = `
                    <span class="badge bg-${statusClass}">${worker.status}</span>
                    <span class="badge bg-${heartbeatClass} ms-1">${worker.heartbeat_status}</span>
                `;
                
                const fioVersionCell = document.createElement("td");
                fioVersionCell.textContent = worker.fio_version || "N/A";
                
                const createdCell = document.createElement("td");
                createdCell.textContent = createdAt;
                
                const actionCell = document.createElement("td");
                actionCell.innerHTML = `
                    <button class="btn btn-sm btn-outline-danger worker-delete-btn" data-id="${worker.id}">
                        <i class="fas fa-trash-alt"></i> 删除
                    </button>
                `;
                
                // 添加行
                row.appendChild(checkboxCell);
                row.appendChild(nameCell);
                row.appendChild(idCell);
                row.appendChild(ipCell);
                row.appendChild(statusCell);
                row.appendChild(fioVersionCell);
                row.appendChild(createdCell);
                row.appendChild(actionCell);
                
                tbody.appendChild(row);
            });
            
            // 重新初始化选择功能
            setTimeout(initializeWorkerSelectionWhenReady, 100);
        })
        .catch(error => {
            console.error("Error loading workers:", error);
            const tbody = document.querySelector("#workersTable tbody");
            if (tbody) {
                tbody.innerHTML = `<tr><td colspan="8" class="text-center text-danger">加载Worker数据失败: ${error.message}</td></tr>`;
            }
        });
}

function updateWorkerStats(workers) {
    // 计算统计数据
    const totalWorkers = workers ? workers.length : 0;
    let onlineWorkers = 0;
    let offlineWorkers = 0;
    let healthyWorkers = 0;
    let warningWorkers = 0;
    let errorWorkers = 0;
    
    if (workers) {
        workers.forEach(worker => {
            if (worker.status === "online") {
                onlineWorkers++;
            } else {
                offlineWorkers++;
            }
            
            if (worker.heartbeat_status === "healthy") {
                healthyWorkers++;
            } else if (worker.heartbeat_status === "warning") {
                warningWorkers++;
            } else if (worker.heartbeat_status === "error") {
                errorWorkers++;
            }
        });
    }
    
    // 更新页面上的统计数字
    const totalEl = document.getElementById("totalWorkers");
    const onlineEl = document.getElementById("onlineWorkers");
    const offlineEl = document.getElementById("offlineWorkers");
    const healthyEl = document.getElementById("healthyWorkers");
    
    if (totalEl) totalEl.textContent = totalWorkers;
    if (onlineEl) onlineEl.textContent = onlineWorkers;
    if (offlineEl) offlineEl.textContent = offlineWorkers;
    if (healthyEl) healthyEl.textContent = healthyWorkers;
}

function initializeWorkerSelectionWhenReady() {
    const selectAllCheckbox = document.getElementById("selectAll");
    const workerCheckboxes = document.querySelectorAll(".worker-select");
    const deleteBtn = document.getElementById("batchDeleteBtn");
    
    if (!selectAllCheckbox || workerCheckboxes.length === 0 || !deleteBtn) {
        // 如果元素还没准备好，稍后重试
        setTimeout(initializeWorkerSelectionWhenReady, 100);
        return;
    }
    
    console.log("All required elements found, initializing worker selection");
    
    // 全选/取消全选功能
    selectAllCheckbox.addEventListener("change", function() {
        workerCheckboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        updateDeleteButtonState();
    });
    
    // 单个复选框选择事件
    workerCheckboxes.forEach(checkbox => {
        checkbox.addEventListener("change", function() {
            updateSelectAllCheckbox();
            updateDeleteButtonState();
        });
    });
    
    // 初始化删除按钮状态
    updateDeleteButtonState();
}

function updateSelectAllCheckbox() {
    const selectAllCheckbox = document.getElementById("selectAll");
    const workerCheckboxes = document.querySelectorAll(".worker-select");
    
    if (selectAllCheckbox && workerCheckboxes.length > 0) {
        const allChecked = Array.from(workerCheckboxes).every(checkbox => checkbox.checked);
        const anyChecked = Array.from(workerCheckboxes).some(checkbox => checkbox.checked);
        
        selectAllCheckbox.checked = allChecked;
        selectAllCheckbox.indeterminate = !allChecked && anyChecked; // 半选状态
    }
}

function updateDeleteButtonState() {
    const selectedCheckboxes = document.querySelectorAll(".worker-select:checked");
    const deleteBtn = document.getElementById("batchDeleteBtn");
    
    if (selectedCheckboxes.length > 0) {
        deleteBtn.disabled = false;
        deleteBtn.classList.remove("btn-outline-danger");
        deleteBtn.classList.add("btn-danger");
        // Make sure it"s visible by removing d-none if it exists
        deleteBtn.classList.remove("d-none");
    } else {
        deleteBtn.disabled = true;
        deleteBtn.classList.remove("btn-danger");
        deleteBtn.classList.add("btn-outline-danger");
    }
}

function deleteSelectedWorkers() {
    const selectedCheckboxes = document.querySelectorAll(".worker-select:checked");
    
    if (selectedCheckboxes.length === 0) {
        return; // 按钮应该被禁用，但以防万一
    }
    
    const selectedIds = Array.from(selectedCheckboxes).map(checkbox => checkbox.dataset.id);
    
    if (confirm(`确定要删除选中的 ${selectedIds.length} 个Worker吗？`)) {
        // 调用API批量删除Worker
        fetch("/api/workers/batch-delete", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ ids: selectedIds })
        })
        .then(async response => {
            const txt = await response.text();
            try { return { statusCode: response.status, body: JSON.parse(txt || '{}') }; }
            catch(e) { return { statusCode: response.status, body: txt }; }
        })
        .then(data => {
            if (data.body && (data.body.status === "success" || data.body.status === "partial")) {
                // 确保清理可能的遮罩
                document.body.classList.remove('modal-open');
                const existingBackdrop = document.querySelector('.modal-backdrop');
                if (existingBackdrop) {
                    existingBackdrop.remove();
                }
                
                // 重新加载页面或刷新工作列表
                loadWorkers(); // 刷新worker列表而不是重载整个页面
                showNotification(`成功删除了 ${data.body.deleted_count} 个Worker`, 'success');
            } else {
                showNotification("删除失败: " + (typeof data.body === 'string' ? data.body : (data.body && data.body.error) || "未知错误"), 'error');
            }
        })
        .catch(error => {
            console.error("Error:", error);
            showNotification("删除过程中发生错误: " + error.message, 'error');
        });
    }
}

// 立即尝试初始化，如果失败则设置定时器重试
if (document.readyState === "loading") {
    // 页面仍在加载中
    document.addEventListener("DOMContentLoaded", function() {
        setTimeout(initializeWorkerSelectionWhenReady, 100);
        loadWorkers(); // 页面加载完成后加载worker列表
    });
} else {
    // 页面已加载完成
    setTimeout(initializeWorkerSelectionWhenReady, 100);
    loadWorkers(); // 直接加载worker列表
}

// 为每个单独的删除按钮添加事件监听器
document.addEventListener("click", function(e) {
    if (e.target.classList.contains("worker-delete-btn") || (e.target.parentElement && e.target.parentElement.classList.contains("worker-delete-btn"))) {
        const button = e.target.classList.contains("worker-delete-btn") ? e.target : e.target.parentElement;
        const workerId = button.getAttribute("data-id");
        if (confirm("确定要删除这个Worker吗？")) {
            fetch(`/api/workers/${workerId}`, {
                method: "DELETE",
                headers: {
                    "Content-Type": "application/json",
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === "success") {
                    // 确保清理可能的遮罩
                    document.body.classList.remove('modal-open');
                    const existingBackdrop = document.querySelector('.modal-backdrop');
                    if (existingBackdrop) {
                        existingBackdrop.remove();
                    }
                    
                    loadWorkers(); // 刷新worker列表而不是重载整个页面
                    showNotification("Worker删除成功！", 'success');
                } else {
                    showNotification("删除失败: " + (data.error || "未知错误"), 'error');
                }
            })
            .catch(error => {
                console.error("Error:", error);
                showNotification("删除过程中发生错误: " + error.message, 'error');
            });
        }
    }
});

// 绑定批量删除按钮（直接绑定到元素，避免点击按钮内部图标导致事件不触发的问题）
document.addEventListener('DOMContentLoaded', function() {
    const batchBtn = document.getElementById('batchDeleteBtn');
    if (batchBtn) {
        batchBtn.addEventListener('click', function() {
            if (!this.disabled) {
                deleteSelectedWorkers();
            }
        });
    }
});

// 添加刷新按钮事件（如果存在）
document.addEventListener("click", function(e) {
    if (e.target.id === "refreshWorkersBtn" || (e.target.parentElement && e.target.parentElement.id === "refreshWorkersBtn")) {
        loadWorkers();
    }
});

// 添加通知功能
function showNotification(message, type = 'info') {
    // 创建一个临时的通知元素
    const notification = document.createElement('div');
    notification.className = `alert alert-${type === 'error' ? 'danger' : type} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; min-width: 300px; z-index: 9999;';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (notification.parentNode) {
            notification.remove();
        }
    }, 3000);
}

